//
//  AZCharacteristicViewController.m
//  AZBLE
//
//  Created by AZ-Mac on 2017/5/2.
//  Copyright © 2017年 AZ-Mac. All rights reserved.
//

#import "AZCharacteristicViewController.h"
#import "BLETool.h"
#import "AZCharcteristicCell.h"
#import "AZValueModel.h"
#import "AZSendDataController.h"
#import "AZSendDataTypeController.h"
#import <SWHex.h>
@interface AZCharacteristicViewController ()<CBPeripheralDelegate,UITableViewDelegate,UITableViewDataSource>
@property (weak, nonatomic) IBOutlet UITableView *characteristicTableView;
@property(strong,nonatomic) BLETool *ble;
@property(strong,nonatomic) NSMutableArray *valueArray;
@end
@implementation AZCharacteristicViewController
- (NSMutableArray *)valueArray
{
    if(!_valueArray)
    {
        _valueArray = [NSMutableArray array];
    }
    return _valueArray;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self initUI];
}
static NSString *charcteristicCell = @"charcteristicCell";
- (void)initUI
{
    // 监听键盘通知
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillChangeFrame:) name:UIKeyboardWillChangeFrameNotification object:nil];
    
    [self.peripheral setNotifyValue:YES forCharacteristic:self.characteristic];
    self.peripheral.delegate = self;

    self.navigationItem.title = [NSString stringWithFormat:@"%@",self.characteristic.UUID];
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc]initWithTitle:@"Hed" style:UIBarButtonItemStyleDone target:self action:@selector(rightNavClick)];
    self.characteristicTableView.delegate = self;
    self.characteristicTableView.dataSource = self;
    [self.characteristicTableView registerNib:[UINib nibWithNibName:@"AZCharcteristicCell" bundle:nil] forCellReuseIdentifier:charcteristicCell];
}
- (void)rightNavClick
{
    AZSendDataTypeController * scaleTypeVc =  [[AZSendDataTypeController alloc]init];
    
    __weak AZCharacteristicViewController *weakSelf = self;
    scaleTypeVc.scaleType = ^(ScaleType scaleType){
        weakSelf.scaleType = scaleType;
    };
    
    [self.navigationController pushViewController:scaleTypeVc animated:YES];
}
#pragma mark - 键盘处理
- (void)keyboardWillChangeFrame:(NSNotification *)note {
    // 取出键盘最终的frame
    CGRect rect = [note.userInfo[UIKeyboardFrameEndUserInfoKey] CGRectValue];
    // 取出键盘弹出需要花费的时间
    double duration = [note.userInfo[UIKeyboardAnimationDurationUserInfoKey] doubleValue];
    // 修改transform
    [UIView animateWithDuration:duration animations:^{
        CGFloat ty = [UIScreen mainScreen].bounds.size.height - rect.origin.y;
        self.view.transform = CGAffineTransformMakeTranslation(0, - ty);
    }];
}
/**
 发送数据按钮
 */
- (IBAction)sendClick:(id)sender {
    
    AZSendDataController *sendDataVc = [AZSendDataController new];
    
    [self.navigationController pushViewController:sendDataVc animated:YES];
    
    __weak AZCharacteristicViewController *weakSelf = self;
    
    sendDataVc.sendValue = ^(NSString *sendString){
        NSData *sendData;
        switch (weakSelf.scaleType) {
            case ScaleTypeUTF8:
                sendData = [sendString dataUsingEncoding:NSUTF8StringEncoding];
                break;
            case ScaleTypeHex:
                sendData = [sendString dataFromBytesString];
                break;
            default:
                break;
        }
        //发送数据
        [weakSelf azCBPeripheral:self.peripheral writeValue:sendData forCharacteristic:self.characteristic response:NO];
        //更新UI
        [weakSelf.valueArray addObject:[AZValueModel modelFromValueType:valueTypeSend Value:sendString]];
        [weakSelf.characteristicTableView reloadData];
        [weakSelf.view endEditing:YES];
        [weakSelf.characteristicTableView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:(self.valueArray.count - 1) inSection:0] atScrollPosition:UITableViewScrollPositionBottom animated:YES];
    };
}
/**
 发送数据统一方法
 */
- (void)azCBPeripheral:(CBPeripheral* )peripheral writeValue:(NSData *)data forCharacteristic:(CBCharacteristic *)characteristic response:(BOOL)response
{
    NSLog(@"peripheralName:%@写入characteristicUUID:%@ Data：%@",peripheral.name,characteristic,data);
    [peripheral writeValue:data forCharacteristic:characteristic type:CBCharacteristicWriteWithoutResponse];
}
/**
 获取外设发来的数据，不论是read和notify,获取数据都是从这个方法中读取。
 */
- (void)peripheral:(CBPeripheral *)peripheral didUpdateValueForCharacteristic:(CBCharacteristic *)characteristic error:(nullable NSError *)error
{
    NSLog(@"特征值更新%s, line = %d, characteristic.UUID:%@  value:%@", __FUNCTION__, __LINE__, characteristic.UUID, characteristic.value);    //此句不要注释，需要用来调试
    NSData *recData = characteristic.value;
    NSString *showString ;
    switch (self.scaleType) {
        case ScaleTypeUTF8:
            showString = [[NSString alloc]initWithData:recData encoding:NSUTF8StringEncoding];
            break;
        case ScaleTypeHex:
            showString = [recData bytesString];
            break;
        default:
            break;
    }
    [self.valueArray addObject:[AZValueModel modelFromValueType:valueTypeReceive Value:showString]];
    
    dispatch_sync(dispatch_get_main_queue(), ^{
        [self.characteristicTableView reloadData];
        [self.characteristicTableView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:(self.valueArray.count - 1) inSection:0] atScrollPosition:UITableViewScrollPositionBottom animated:YES];
    });
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    NSLog(@"self.valueArray.count:%d",self.valueArray.count);
    return  self.valueArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    AZCharcteristicCell *cell = [tableView dequeueReusableCellWithIdentifier:charcteristicCell];

    AZValueModel *model = self.valueArray[indexPath.row];
    cell.model = model;
    return cell;
}
- (void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}
-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
    [self.view endEditing:YES];
}
@end
